//
//  SYSensorManager.m
//  SYCompassDemo
//
//  Created by 陈蜜 on 16/6/27.
//  Copyright © 2016年 sunyu. All rights reserved.
//

#import "SYSensorManager.h"

@interface SYSensorManager () <CLLocationManagerDelegate>

@property (nonatomic, strong) CLLocationManager *manager;
@property (nonatomic, strong) CMMotionManager *motionManager;

@end

@implementation SYSensorManager

+ (instancetype)shared
{
    return [[self alloc]init];
}

- (instancetype)init
{
    if (self = [super init]) {
        
    }
    return self;
}

- (void)startSensor
{
    _manager = [[CLLocationManager alloc]init];
    _manager.delegate = self;
    
    if ([CLLocationManager headingAvailable]) {
        _manager.headingFilter = 5;
        [_manager startUpdatingHeading];
    }
}

- (void)startGyroscope
{
    _motionManager = [[CMMotionManager alloc]init];
    
    if (_motionManager.deviceMotionAvailable) {
        _motionManager.deviceMotionUpdateInterval = 0.01f;
        __weak typeof(self)mySelf = self;
        [_motionManager startDeviceMotionUpdatesToQueue:[NSOperationQueue mainQueue]
                                     withHandler:^(CMDeviceMotion *data, NSError *error) {
                                         [mySelf handleData:data error:error];
                                         if (mySelf.updateDeviceMotionBlock) {
                                             mySelf.updateDeviceMotionBlock(data);
                                         }
                                         
                                     }];
        
    }
}

- (void)handleData:(CMDeviceMotion *)data error:(NSError *)error {
    NSMutableDictionary *resultDic = [[NSMutableDictionary alloc] initWithCapacity:0];
    if (data) {
        NSMutableDictionary *dataDic = [[NSMutableDictionary alloc] initWithCapacity:0];
        NSDictionary *attitudeDic = @{
                                      @"roll": @(data.attitude.roll),
                                      @"pitch": @(data.attitude.pitch),
                                      @"yaw": @(data.attitude.yaw),
                                      @"rotationMatrix": @{
                                              @"m11": @(data.attitude.rotationMatrix.m11),
                                              @"m12": @(data.attitude.rotationMatrix.m12),
                                              @"m13": @(data.attitude.rotationMatrix.m13),
                                              @"m21": @(data.attitude.rotationMatrix.m21),
                                              @"m22": @(data.attitude.rotationMatrix.m22),
                                              @"m23": @(data.attitude.rotationMatrix.m23),
                                              @"m31": @(data.attitude.rotationMatrix.m31),
                                              @"m32": @(data.attitude.rotationMatrix.m32),
                                              @"m33": @(data.attitude.rotationMatrix.m33),
                                              },
                                      @"quaternion": @{
                                              @"x": @(data.attitude.quaternion.x),
                                              @"y": @(data.attitude.quaternion.y),
                                              @"z": @(data.attitude.quaternion.z),
                                              @"w": @(data.attitude.quaternion.w),
                                              }
                                      
                                      };
        dataDic[@"attitude"] = attitudeDic;
        
        NSDictionary *rotationRateDic = @{
                                          @"x": @(data.rotationRate.x),
                                          @"y": @(data.rotationRate.y),
                                          @"z": @(data.rotationRate.z),
                                          };
        dataDic[@"rotationRate"] = rotationRateDic;
        
        NSDictionary *gravityDic = @{
                                     @"x": @(data.gravity.x),
                                     @"y": @(data.gravity.y),
                                     @"z": @(data.gravity.z),
                                     };
        dataDic[@"gravity"] = gravityDic;
        NSLog(@"%@", rotationRateDic);
        
        NSDictionary *userAccelerationDic = @{
                                              @"x": @(data.userAcceleration.x),
                                              @"y": @(data.userAcceleration.y),
                                              @"z": @(data.userAcceleration.z),
                                              };
        dataDic[@"userAcceleration"] = userAccelerationDic;
        
        NSDictionary *magneticFieldDic = @{
                                           @"field": @{
                                                   @"x": @(data.magneticField.field.x),
                                                   @"y": @(data.magneticField.field.y),
                                                   @"z": @(data.magneticField.field.z),
                                                   },
                                           @"accuracy": @(data.magneticField.accuracy),
                                           };
        dataDic[@"magneticField"] = magneticFieldDic;
        dataDic[@"heading"] = @(data.heading);
        
        resultDic[@"data"] = dataDic;
    }
    
    if (error) {
        NSDictionary *errorDic = @{
                                   @"code": @(error.code),
                                   @"domain": error.domain ?:@"",
                                   @"msg": error.localizedDescription?:@"",
                                   };
        resultDic[@"error"] = errorDic;
    }
    
    NSError* err = nil;
    id result = [NSJSONSerialization dataWithJSONObject:resultDic
                                                options:kNilOptions error:&err];
    NSString *jsonString = [[NSString alloc] initWithData:result
                                                 encoding:NSUTF8StringEncoding];
}

- (void)stopGyroscope {
    if (_motionManager) {
        [_motionManager stopDeviceMotionUpdates];
        _motionManager = nil;
    }
}

- (void)stopSensor
{
    [_manager stopUpdatingHeading];
    _manager = nil;
}


#pragma mark - CLLocationManagerDelegate
- (void)locationManager:(CLLocationManager *)manager didUpdateHeading:(CLHeading *)newHeading
{
    if (newHeading.headingAccuracy < 0)
        return;
    
    CLLocationDirection  theHeading = ((newHeading.trueHeading > 0) ?
                                       newHeading.trueHeading : newHeading.magneticHeading);
    if (_didUpdateHeadingBlock) {
        _didUpdateHeadingBlock(theHeading);
    }
}


@end
